<title>External access (UPnP)</title>
<div style="text-align:center" class="upnp-access">
  <p>You can connect to this host from local network <a target="_blank"></a>
    <button type="button" class="btn btn-warning btn-sm" title="Show explanation">QR</button>
  </p>
  <p>Current state of public access is: <strong><span>Unknown</span></strong> at: <a target="_blank"></a>
    <button type="button" class="btn btn-warning btn-sm" title="Show explanation">QR</button>
  </p>
  <button type="button" class="btn btn-secondary upnp-open disabled" data-toggle="toggle" mode="open" title="Open external public port">Open</button>
  <button type="button" class="btn btn-secondary upnp-close disabled" data-toggle="toggle" mode="close" title="Close external public port">Close</button>
<script>
$(function(){
  var base=$('.upnp-access');
  $.ajax('/upnp/local')
  .then(function(data){
    var url='http://'+data.ip+':'+data.port;
    base.find('p:eq(0) a').text(url).attr('href',url);
  });
  function setState(data){
    var url='',state='Closed';
    if (data){
      state=('Opened');
      url='http://'+data.ip+':'+data.port;
    }
    base.find('p:eq(1) span').text(state);
    base.find('p:eq(1) a').text(url).attr('href',url);
  }
  $.ajax('/upnp/check')
  .then(function(data){
    base.find('button').removeClass('disabled')
    setState(data&&data.length&&data[0])
  });
  base.find('.upnp-close,.upnp-open').on('click',function(){
    if ($(this).hasClass('disabled')) return;
    $.ajax('/upnp/'+$(this).attr('mode'))
    .then(function(data){
      setState(data);
    });
  })
  base.find('.btn-warning').on('click',function(){
    var url=$(this).siblings('a').attr('href');
    var m=$('#mct-qr-modal');
    m.find('.modal-body img').attr('src','/qr/'+encodeURI(btoa(url)))
    m.modal();
  });
});
</script>
